package com.feng.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feng.chat.common.Common;
import com.feng.chat.dto.ArticleAnneDTO;
import com.feng.chat.dto.ArticleDetailDTO;
import com.feng.chat.dto.ArticleListDTO;
import com.feng.chat.dto.Result;
import com.feng.chat.entity.Article;
import com.feng.chat.entity.ArticleAnnex;
import com.feng.chat.entity.ArticleClass;
import com.feng.chat.entity.ArticleDetail;
import com.feng.chat.mapper.ArticleAnnexMapper;
import com.feng.chat.mapper.ArticleClassMapper;
import com.feng.chat.mapper.ArticleDetailMapper;
import com.feng.chat.mapper.ArticleMapper;
import com.feng.chat.service.IArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.chat.utils.HtmlUtil;
import com.feng.chat.vo.PaginateVO;
import com.feng.chat.vo.TagsVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户笔记表 服务实现类
 * </p>
 *
 * @author dyf
 * @since 2022-05-31
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleClassMapper articleClassMapper;

    @Autowired
    private ArticleDetailMapper articleDetailMapper;

    @Autowired
    private ArticleAnnexMapper articleAnnexMapper;

    /**
     * 获取笔记列表
     *
     * @param uid
     * @param page
     * @param keyword
     * @param find_type 1:获取近期日记  2:获取星标日记  3:获取指定分类文章  4:获取指定标签文章 5:获取已删除文章 6:关键词搜索
     * @param cid
     * @return
     */
    @Override
    public Result articleList(Integer uid, Integer page, String keyword, Integer find_type, Integer cid) {
        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        articleQueryWrapper.eq("user_id", uid);
        List<Article> recentArticle = null;
        if (find_type == 1) {
            recentArticle = articleMapper.getRecentArticle(uid);
        } else if (find_type == 2) {
            articleQueryWrapper.eq("is_asterisk", 1).eq("status", 1);
            recentArticle = articleMapper.selectList(articleQueryWrapper);
        } else if (find_type == 3) {
            articleQueryWrapper.eq("class_id", cid).eq("status", 1);
            recentArticle = articleMapper.selectList(articleQueryWrapper);
        } else if (find_type == 4) {
            recentArticle = articleMapper.getTagArticle(cid, uid);
        } else if (find_type == 5) {
            articleQueryWrapper.eq("status", 2);
            recentArticle = articleMapper.selectList(articleQueryWrapper);
        } else if (find_type == 6) {
            articleQueryWrapper.eq("status",1).and(wrapper->wrapper.like("title",keyword).or().like("summary",keyword));
            recentArticle = articleMapper.selectList(articleQueryWrapper);
        }

        List<ArticleListDTO> articleListDTOS = new ArrayList<>();
        if (recentArticle!=null){
            articleListDTOS=recentArticle.stream().map(item->{
                ArticleListDTO articleListDTO = new ArticleListDTO();
                ArticleClass articleClass = articleClassMapper.selectById(item.getClassId());
                articleListDTO.setClass_id(item.getClassId());
                articleListDTO.setClass_name(articleClass.getClassName());
                articleListDTO.setCreated_at(item.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
                articleListDTO.setId(item.getId());
                articleListDTO.setImage(item.getImage());
                articleListDTO.setIs_asterisk(item.getIsAsterisk());
                articleListDTO.setStatus(item.getStatus());
                articleListDTO.setSummary(item.getSummary());
                articleListDTO.setTags_id(item.getTagsId());
                if (item.getTitle()!=null){
                    articleListDTO.setTitle(item.getTitle());
                }else {
                    articleListDTO.setTitle("请编辑标题！！！");
                }
                articleListDTO.setUpdated_at(item.getUpdatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
                return articleListDTO;
            }).collect(Collectors.toList());
        }
        PageHelper.startPage(page,1000);
        PageInfo<ArticleListDTO> articleListDTOPageInfo = new PageInfo<>(articleListDTOS);

        PaginateVO paginateVO = new PaginateVO();
        paginateVO.setTotal(articleListDTOPageInfo.getTotal());
        paginateVO.setPage(page);
        paginateVO.setSize(1000);

        Map<String, Object> map = new HashMap<>();
        map.put("rows",articleListDTOPageInfo.getList());
        map.put("paginate",paginateVO);
        return Result.success(map);
    }

    /**
     * 上传笔记图片
     * @param image
     * @return
     */
    @Override
    public Result uploadImage(MultipartFile image) {
        String path="E:\\Desktop\\案例\\javaweb案例\\MyChat\\resource\\article\\";
        String oldFileName = image.getOriginalFilename();
        String suffix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "")+"."+suffix;
        path=path+newFileName;
        File file = new File(path);
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        try {
            image.transferTo(file);
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        }

        String url=" http://localhost:8081/article/"+newFileName;

        Map<String, String> map = new HashMap<>();
        map.put("url",url);
        return Result.success(map);
    }

    /**
     * 编辑笔记
     * @param uid
     * @param article_id
     * @param class_id
     * @param content
     * @param md_content
     * @param title
     * @return
     */
    @Override
    public Result articleEditor(Integer uid, Integer article_id, Integer class_id, String content, String md_content, String title) {
        Article article = new Article();
        String image = HtmlUtil.getImageSrc(content);
        article.setUserId(uid);
        article.setClassId(class_id);
        article.setTitle(title);
        article.setSummary(md_content);
        article.setImage(image);

        ArticleDetail articleDetail = new ArticleDetail();
        articleDetail.setContent(content);
        articleDetail.setMdContent(md_content);

        if (article_id==0){//添加笔记
            articleMapper.insert(article);
            articleDetail.setArticleId(article.getId());
            articleDetailMapper.insert(articleDetail);

            ArticleListDTO articleListDTO = new ArticleListDTO();
            articleListDTO.setSummary(md_content);
            articleListDTO.setTitle(title);
            articleListDTO.setId(article.getId());
            articleListDTO.setImage(image);
            return Result.success(articleListDTO);
        }else {//修改笔记
            article.setId(article_id);
            articleMapper.updateById(article);

            QueryWrapper<ArticleDetail> articleDetailQueryWrapper = new QueryWrapper<>();
            articleDetailQueryWrapper.eq("article_id",article_id);
            ArticleDetail detail = articleDetailMapper.selectOne(articleDetailQueryWrapper);
            detail.setMdContent(md_content);
            detail.setContent(content);
            articleDetailMapper.updateById(detail);

            ArticleListDTO articleListDTO = new ArticleListDTO();
            articleListDTO.setSummary(md_content);
            articleListDTO.setTitle(title);
            articleListDTO.setId(article_id);
            articleListDTO.setImage(image);
            return Result.success(articleListDTO);
        }
    }

    /**
     * 查询笔记详细信息
     * @param article_id
     * @return
     */
    @Override
    public Result articleDetail(Integer article_id) {
        ArticleDetailDTO articleDetailDTO = new ArticleDetailDTO();
        Article article = articleMapper.selectById(article_id);
        articleDetailDTO.setClass_id(article.getClassId());
        articleDetailDTO.setCreated_at(article.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
        articleDetailDTO.setUpdated_at(article.getUpdatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
        articleDetailDTO.setId(article.getId());
        articleDetailDTO.setIs_asterisk(article.getIsAsterisk());
        articleDetailDTO.setStatus(article.getStatus());
        articleDetailDTO.setTitle(article.getTitle());

        List<TagsVO> tagsVOS = new ArrayList<>();
        if (article.getTagsId()!=null){
            List<String> tagIds = Arrays.asList(article.getTagsId().split(","));
            tagsVOS=tagIds.stream().map(item->{
                TagsVO tagsVO = new TagsVO();
                tagsVO.setId(Integer.parseInt(item));
                return tagsVO;
            }).collect(Collectors.toList());

        }
        articleDetailDTO.setTags(tagsVOS);

        QueryWrapper<ArticleDetail> articleDetailQueryWrapper = new QueryWrapper<>();
        articleDetailQueryWrapper.eq("article_id",article_id);
        ArticleDetail articleDetail = articleDetailMapper.selectOne(articleDetailQueryWrapper);
        articleDetailDTO.setContent(articleDetail.getContent());
        articleDetailDTO.setMd_content(articleDetail.getMdContent());

        QueryWrapper<ArticleAnnex> articleAnnexQueryWrapper = new QueryWrapper<>();
        articleAnnexQueryWrapper.eq("article_id",article_id).eq("status",1);
        List<ArticleAnnex> articleAnnexes = articleAnnexMapper.selectList(articleAnnexQueryWrapper);
        List<ArticleAnneDTO> articleAnneDTOS = new ArrayList<>();
        articleAnneDTOS=articleAnnexes.stream().map(item->{
            ArticleAnneDTO articleAnneDTO = new ArticleAnneDTO();
            articleAnneDTO.setId(item.getId());
            articleAnneDTO.setCreated_at(item.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
            articleAnneDTO.setOriginal_name(item.getOriginalName());
            articleAnneDTO.setSize(item.getSize());
            articleAnneDTO.setSuffix(item.getSuffix());
            return articleAnneDTO;
        }).collect(Collectors.toList());
        articleDetailDTO.setFiles(articleAnneDTOS);
        return Result.success(articleDetailDTO);
    }

    /**
     * 设置星标笔记
     * @param article_id
     * @param type
     * @return
     */
    @Override
    public Result articleAsterisk(Integer article_id, Integer type) {
        Article article = articleMapper.selectById(article_id);
        if (type==1){//添加为星标笔记
            article.setIsAsterisk(1);
        }else if (type==2){//移除星标笔记
            article.setIsAsterisk(0);
        }
        articleMapper.updateById(article);

        return Result.success();
    }

    /**
     * 删除笔记
     * @param article_id
     * @return
     */
    @Override
    public Result articleDelete(Integer article_id) {
        Article article = articleMapper.selectById(article_id);
        article.setStatus(2);
        article.setDeletedAt(LocalDateTime.now());
        articleMapper.updateById(article);
        return Result.success();
    }

    /**
     * 恢复笔记
     * @param article_id
     * @return
     */
    @Override
    public Result articleRecover(Integer article_id) {
        Article article = articleMapper.selectById(article_id);
        article.setStatus(1);
        article.setDeletedAt(null);
        articleMapper.updateById(article);
        return Result.success();
    }

    /**
     * 永久删除笔记回收站的笔记
     * @param article_id
     * @return
     */
    @Override
    public Result foreverDelete(Integer article_id) {
        Article article = articleMapper.selectById(article_id);
        article.setStatus(3);
        article.setDeletedAt(LocalDateTime.now());
        articleMapper.updateById(article);
        return Result.success();
    }
}
